<template>
  <view class="settings-container">
    <view class="section">
      <text class="label">服务器IP地址</text>
      <input
        v-model="serverIP"
        placeholder="请输入IP:端口，例如 192.168.1.8:8000"
        class="input-box"
      />
    </view>

    <view class="section">
      <text class="label">写入数据库</text>
      <!-- ✅ 改为 :checked 和 @change -->
      <switch :checked="writeToDB" @change="onWriteToDBChange" />
    </view>

    <button class="save-btn" @click="saveSettings">保存</button>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'

const serverIP = ref("")
const writeToDB = ref(false) // 默认关闭写入数据库

// 页面加载时读取设置
onMounted(() => {
  const savedIP = uni.getStorageSync("server_ip")
  const savedWriteFlag = uni.getStorageSync("write_to_db")

  if (savedIP) serverIP.value = savedIP
  if (savedWriteFlag !== "") writeToDB.value = !!savedWriteFlag
})

// 保存设置
function saveSettings() {
  if (!serverIP.value) {
    uni.showToast({ title: "请输入服务器IP", icon: "none" })
    return
  }
  uni.setStorageSync("server_ip", serverIP.value)
  uni.setStorageSync("write_to_db", writeToDB.value)

  uni.showToast({ title: "设置已保存", icon: "success" })

  setTimeout(() => {
    uni.navigateBack()
  }, 800)
}


// ✅ 监听开关变化
function onWriteToDBChange(e: any) {
  writeToDB.value = e.detail.value
}
</script>

<style>
.settings-container {
  flex: 1;
  padding: 30rpx;
  background-color: #fff;
}

.section {
  margin-bottom: 30rpx;
}

.label {
  font-size: 30rpx;
  margin-bottom: 10rpx;
  display: block;
}

.input-box {
  border: 1rpx solid #ddd;
  padding: 15rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.save-btn {
  background-color: #007aff;
  color: #fff;
  font-size: 32rpx;
  padding: 20rpx;
  border-radius: 10rpx;
  text-align: center;
}
</style>
